package com.gensdai.leliang.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.classic.common.MultipleStatusView;
import com.facebook.drawee.view.SimpleDraweeView;
import com.gensdai.leliang.AppApplication;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.adapter.HotProductYouLikeAdapterRec;
import com.gensdai.leliang.common.clickinterface.OnProductClickListener;
import com.gensdai.leliang.dialog.FilterMultPopup;
import com.gensdai.leliang.dialog.FilterPricePopup;
import com.gensdai.leliang.entity.HomeBean;
import com.gensdai.leliang.entity.parseBean.BaseParseList;
import com.gensdai.leliang.entity.parseBean.ProductInfo;
import com.gensdai.leliang.popupwindow.BasePopupWindow;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.retrofitUtils.exception.APIException;
import com.gensdai.leliang.utils.BaseUtils;
import com.gensdai.leliang.view.Toaster;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import retrofit2.HttpException;

/**
 * 品牌内页
 * Created by zsxx on 2017/7/28.
 */

public class ActivityBrand extends BaseActivity {
    public static final String EXTRA_BRAND_ID = "extrabrandid";
    @BindView(R.id.icon)
    SimpleDraweeView icon;

    HomeBean.BrandBean menu;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.product_recycler)
    RecyclerView productRecycler;


    LinearLayoutManager layoutManager;

    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;

    FilterPricePopup mPriceWindow;
    FilterMultPopup mMultWindow;
    @BindView(R.id.priceFilter)
    TextView priceFilter;
    @BindView(R.id.stockFilter)
    TextView stockFilter;
    @BindView(R.id.filter)
    TextView filter;
    @BindView(R.id.brand_multiplestatusview)
    MultipleStatusView brandMultiplestatusview;

    //    FilterPopupWindow mFilterWindow;

    /*价格高低排序 （”1”价格由高到低 ， “2”价格由低到高 ， 0则不筛选）*/
    private int priceSort = 0;
    /*销量优先（”1”销量由高到低 ， 0则不筛选）*/
    private int saleNum = 0;
    private String highestPrice = "";
    private String lowestPrice = "";
    private String  ifNew = "";

    @Override
    protected String getTitleStr() {
        return "品牌详情";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_brand;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        menu = (HomeBean.BrandBean) getIntent().getSerializableExtra(EXTRA_BRAND_ID);
        ButterKnife.bind(this);

        initRecycler();
        initPriceFilterWindow();
        initMuiltFilterWindow();
        if (menu != null) {
            getSupportActionBar().setTitle(menu.brandName);
            icon.setImageURI(Uri.parse(menu.brandLogo));
            title.setText(menu.brandName + "品牌专场");
            getProductList();
        }

        //设置重试视图点击事件
        brandMultiplestatusview.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getProductList();
            }
        });

//        test.setImageBitmap(getBitmapFromURL("http://192.168.1.91/lelongApp/make_verify_code.html"));
//

    }



    private void initMuiltFilterWindow() {
        mMultWindow = new FilterMultPopup(this);
        mMultWindow.init();
//        mMultWindow.setShowAtDown(true);
        mMultWindow.setOffsetY(getResources().getDimensionPixelOffset(R.dimen.px92dp));
        mMultWindow.setOnBtnClickListener(new FilterMultPopup.OnBtnClickListener() {

            @Override
            public void onDoneClick(boolean isnew, String lowprice, String hightprice,BasePopupWindow p) {
                highestPrice = hightprice;
                lowestPrice = lowprice;
                ifNew = isnew?"1":"";

                if(p.isShowing()){
                    p.dismiss();
                }

                if(!isnew && TextUtils.isEmpty(lowprice) && TextUtils.isEmpty(hightprice)){
                    filter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.producttitleColor));
                }else{
                    filter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.baseColor));
                }
                getProductList();
            }
        });
    }


    private void initPriceFilterWindow() {
        mPriceWindow = new FilterPricePopup(this);
        mPriceWindow.init();
        mPriceWindow.setOffsetY(getResources().getDimensionPixelOffset(R.dimen.px92dp));
//        mPriceWindow.setShowAtDown(true);
        mPriceWindow.setOnItemClickListener(new FilterPricePopup.onPriceItemClick() {
            @Override
            public void onPriceSortItemClick(String t, BasePopupWindow p,int type) {
                priceFilter.setText(t);
                priceFilter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.baseColor));
                stockFilter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.producttitleColor));
                if (p.isShowing()) {
                    p.dismiss();
                }

                //选中筛选后标记要传的值
                priceSort = type;
                saleNum = 0;

                getProductList();

            }


            @Override
            public void onResetListener(String t, BasePopupWindow p) {
                priceFilter.setText(t);
                priceFilter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.producttitleColor));
                //选中销量 默认价格排序为第一个
                priceSort = 0;
            }

        });

        priceFilter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.baseColor));
    }

    @OnClick(R.id.priceFilter)
    public void priceFilterClickListener(View v) {
        if (mPriceWindow != null) {
//            mPriceWindow.setOffsetY(mPriceWindow.getScreenHeight());
            mPriceWindow.showPopupWindow(priceFilter);
        }
    }

    @OnClick(R.id.stockFilter)
    public void stockFilterClickListener(View v) {
        stockFilter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.baseColor));
        if (mPriceWindow != null) {
            mPriceWindow.reset();
            priceFilter.setTextColor(AppApplication.getContext().getResources().getColor(R.color.producttitleColor));
            if (mPriceWindow.isShowing())
                mPriceWindow.dismiss();
        }
        saleNum = 1;

        getProductList();

    }

    @OnClick(R.id.filter)
    public void filterFilterClickListener(View v) {
        if (mMultWindow != null) {
//            mPriceWindow.setOffsetY(mPriceWindow.getScreenHeight());
            mMultWindow.showPopupWindow(priceFilter);

        }

    }


    private void getProductList() {

        if (!BaseUtils.isNetworkAvailable(this)) {
            //没有网络显示无网络
            brandMultiplestatusview.showNoNetwork();
            return;
        }

        Map<String, String> params = new HashMap<>();
        params.put("brandNo", menu.brandId);
        params.put("saleNum", saleNum+"");
        params.put("priceSort",priceSort+"");
        params.put("highestPrice", highestPrice);
        params.put("lowestPrice",lowestPrice);
        params.put("ifNew", ifNew);
        params.put("clientType", AppApplication.ClientType);
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().getBrandDetail(params))
                .compose(this.<BaseParseList<ProductInfo>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }
                        brandMultiplestatusview.showLoading();
                    }
                })
                .subscribe(new BaseObserverList<ProductInfo>(this) {
                    @Override
                    public void onHandleSuccess(List<ProductInfo> t) {
                        attachView(t);
                    }

                    @Override
                    public void onHandleError(int code, String message) {
                        Toaster.showOneToast(code + ":" + message);
                    }
                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                        if (e instanceof APIException) {
                            APIException exception = (APIException) e;
                            Toast.makeText(AppApplication.getContext(), exception.message, Toast.LENGTH_SHORT).show();
                        } else if (e instanceof UnknownHostException) {
                            Toast.makeText(AppApplication.getContext(), "请打开网络", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof SocketTimeoutException) {
                            Toast.makeText(AppApplication.getContext(), "请求超时", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof ConnectException) {
                            Toast.makeText(AppApplication.getContext(), "连接失败", Toast.LENGTH_SHORT).show();
                        } else if (e instanceof HttpException) {
                            Toast.makeText(AppApplication.getContext(), "请求异常" + ((HttpException) e).code(), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(AppApplication.getContext(), "请求失败", Toast.LENGTH_SHORT).show();
                        }

                        brandMultiplestatusview.post(new Runnable() {
                            @Override
                            public void run() {
                                brandMultiplestatusview.showError();
                            }
                        });
                    }
                });
    }

    private void attachView(List<ProductInfo> t) {

        if(t !=null && t.size() > 0){
            GridLayoutHelper layoutHelper = new GridLayoutHelper(2);
            layoutHelper.setPadding(getResources().getDimensionPixelOffset(R.dimen.px30dp), 0, getResources().getDimensionPixelOffset(R.dimen.px30dp), 0);
            layoutHelper.setBgColor(ContextCompat.getColor(this, R.color.bgColor_new));
            layoutHelper.setAutoExpand(false);
            //横间距
            layoutHelper.setHGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
            layoutHelper.setVGap(getResources().getDimensionPixelOffset(R.dimen.px10dp));
            if (adapters != null) {
                adapters.clear();
                HotProductYouLikeAdapterRec menuAdapter = new HotProductYouLikeAdapterRec(this, layoutHelper, t);
                menuAdapter.setOnProductClicklistener(productClickListener);
                adapters.add(menuAdapter);
            }
            //初始化完毕后开始适配

            delegateAdapter.setAdapters(adapters);
            productRecycler.setAdapter(delegateAdapter);

            //延迟3秒后显示内容页面
            brandMultiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    brandMultiplestatusview.showContent();
                }
            }, 500);
        }else{
            //延迟3秒后显示内容页面
            brandMultiplestatusview.postDelayed(new Runnable() {
                @Override
                public void run() {
                    brandMultiplestatusview.showEmpty();
                }
            }, 500);
        }


    }

    OnProductClickListener productClickListener = new OnProductClickListener<ProductInfo>() {
        @Override
        public void OnProductClick(ProductInfo info, int position) {
            startPorductInfo(info.getId());
        }
    };

    //跳转到产品详情页面
    private void startPorductInfo(String pid) {
        Intent it = new Intent(this, ProductDetail.class);
        it.putExtra(ProductDetail.EXTRA_PID, pid/*"0063ed7e81b64fec8e0aa88212987639"*/);
        startActivity(it);
    }


    private void initRecycler() {
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        productRecycler.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        productRecycler.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        adapters = new LinkedList<>();
    }

}
